#ifndef FRAME_PRODUCER_CONSUMER_H
#define FRAME_PRODUCER_CONSUMER_H

#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <memory>
#include "video_frame.h"
#include "frame_processor.h"
#include "frame_statistics.h"

// 帧队列 - 用于生产者-消费者模型
class FrameQueue {
private:
    std::queue<std::shared_ptr<VideoFrame>> queue_;
    mutable std::mutex mutex_;
    std::condition_variable cond_;
    std::atomic<bool> stopped_;
    size_t max_size_;

public:
    explicit FrameQueue(size_t max_size = 100) : stopped_(false), max_size_(max_size) {}
    
    // 停止队列
    void stop() {
        stopped_ = true;
        cond_.notify_all();
    }
    
    // 入队
    bool enqueue(std::shared_ptr<VideoFrame> frame);
    
    // 出队
    bool dequeue(std::shared_ptr<VideoFrame>& frame, int timeout_ms = -1);
    
    // 检查队列是否为空
    bool empty() const {
        std::lock_guard<std::mutex> lock(mutex_);
        return queue_.empty();
    }
    
    // 获取队列大小
    size_t size() const {
        std::lock_guard<std::mutex> lock(mutex_);
        return queue_.size();
    }
};

// 帧生产者 - 模拟帧生成
class FrameProducer {
private:
    FrameQueue& queue_;
    std::thread thread_;
    std::atomic<bool> running_;
    uint64_t next_frame_id_;
    std::mt19937 rng_;
    std::uniform_int_distribution<size_t> frame_size_dist_; // 帧大小分布（字节）
    std::uniform_int_distribution<int> frame_interval_dist_; // 帧间隔分布（毫秒）

public:
    FrameProducer(FrameQueue& queue, size_t min_frame_size = 1024, size_t max_frame_size = 1024 * 100);
    ~FrameProducer();
    
    // 启动生产者
    void start();
    
    // 停止生产者
    void stop();
};

// 帧消费者 - 处理帧并收集统计信息
class FrameConsumer {
private:
    FrameQueue& queue_;
    ProcessingPipeline pipeline_;
    FrameStatistics& statistics_;
    std::thread thread_;
    std::atomic<bool> running_;

public:
    FrameConsumer(FrameQueue& queue, FrameStatistics& statistics);
    ~FrameConsumer();
    
    // 启动消费者
    void start();
    
    // 停止消费者
    void stop();
};

// 统计定时器 - 定期触发统计计算
class StatisticsTimer {
private:
    FrameStatistics& statistics_;
    std::chrono::seconds interval_;
    std::thread thread_;
    std::atomic<bool> running_;

public:
    StatisticsTimer(FrameStatistics& statistics, std::chrono::seconds interval);
    ~StatisticsTimer();
    
    // 启动定时器
    void start();
    
    // 停止定时器
    void stop();
};

#endif // FRAME_PRODUCER_CONSUMER_H
